package main

import (
	"log"
	"net/url"
	"strings"
)

import (
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
)

var (
    wv *walk.WebView    //定义webview窗体
)

type MyWindow struct {
	*walk.MainWindow
	//ni *walk.NotifyIcon	//任务栏图标
}

func NewMyWindow() *MyWindow {
	mw := new(MyWindow)
	var err error
	mw.MainWindow, err = walk.NewMainWindow()
	checkError(err)
	return mw
}

func (mw *MyWindow) msgbox(title, message string, style walk.MsgBoxStyle) {
	//mw.ni.ShowInfo(title, message)		//任务栏显示信息
	walk.MsgBox(mw, title, message, style)
}

//显示提交 满意度调查表的 窗体
func (mw *MyWindow) show() {
    var (
        wv *walk.WebView    //定义webview窗体
        //le *walk.LineEdit	//显示URL的框框
    )
	//mw := NewMyWindow()
	go timer_handle_settitle(mw.MainWindow) 	//开启定时器任务
	if err := (MainWindow{
		AssignTo: &mw.MainWindow,
		Icon:     Bind("'../img/' + icon(wv.URL) + '.ico'"),
		Title:    "华中师范大学多媒体教学使用满意度调查",
		MinSize:  Size{800, 600},
		Layout:   VBox{MarginsZero: true},
		Children: []Widget{
			/*LineEdit{
				AssignTo: &le,
				Text:     Bind("wv.URL"),
				OnKeyDown: func(key walk.Key) {
					if key == walk.KeyReturn {
						wv.SetURL(le.Text())
					}
				},
			},*/ //不要显示URL框
			WebView{
				AssignTo:     &wv,
				Name:         "wv",
				URL:          "http://127.0.0.1:8080/myddc",
				OnURLChanged: mw.t1, //mw.t2, //响应webview的URL改变事件
			},
		},
		Functions: map[string]func(args ...interface{}) (interface{}, error){
			"icon": func(args ...interface{}) (interface{}, error) {
				if strings.HasPrefix(args[0].(string), "https") {
					return "check", nil
				}

				return "stop", nil
			},
		},
	}.Create()); err != nil {
		log.Fatal(err)
	}
	mw.Run()
	chan_timer_handle_exit <- 1 //程序退出时通知协程子处理器退出
}

func (mw *MyWindow) t2() {
	walk.MsgBox(mw, "Change View", "By now you may have guessed it. Nothing changed.", walk.MsgBoxIconInformation)
}

func (mw *MyWindow) t1() {
	//响应webview的URL改变事件
	//mw.FormBase.SetTitle("hehehehe") //更改窗口标题
	var (
		change_url string
		err        error
	)
	change_url, err = wv.URL()             //取得webview的URL
	url_path, err := url.Parse(change_url) //分析URL，取出Path
	log.Println("刷新了网页事件，URL：", change_url, "\n URL path:", url_path.Path)
	if url_path.Path == "/myddcok" { //如果URL的Path是/myddcok则关机
		log.Println("服务器提交成功!关机！")
		//shutdown()
	}
	if err != nil {
		log.Println("取URL错误：", change_url)
	}
}